package com.df.happylearn.request;

import android.content.Context;
import android.text.TextUtils;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.df.happylearn.application.MyApplication;


/**
 * 数据加载器
 */
public class DataLoader {
    public static final String TAG = DataLoader.class
            .getSimpleName();

    private static class SingletonHolder {
        private static final DataLoader INSTANCE = new DataLoader(MyApplication.getInstance());
    }

    private static final int DEFAULT_TIMEOUT_MS = 5000; //设置连接超时时间
    private static final int DEFAULT_MAX_RETRIES = 0; //设置超时从新连接次数

    public static final DataLoader getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private RequestQueue mRequestQueue;
    private final Object mRequestQueueLockobj = new Object();
    private Context mContext;
    private ImageLoader mImageLoader;
    private final Object mImageLoaderLockobj = new Object();

    private DataLoader (Context context)
    {
        mContext = context;
    }

    //请求队列
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            synchronized (mRequestQueueLockobj)
            {
                if(mRequestQueue==null)
                {
                    mRequestQueue = Volley.newRequestQueue(mContext);
                }
            }
        }
        return mRequestQueue;
    }

    //ImageLoader
    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            synchronized (mImageLoaderLockobj)
            {
                if(mImageLoader==null)
                {
                    mImageLoader = new ImageLoader(this.mRequestQueue,
                            new LruBitmapCache());
                }
            }
        }
        return this.mImageLoader;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        req.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}
